﻿using B.S.NewMedical.Api.Read.Application.Command.Order;
using B.S.NewMedical.Api.Read.DTOS;
using B.S.NewMedical.Domain.Order;
using B.S.NewMedical.ErrorCode;
using B.S.NewMedical.Infrastructure.Interface;
using MediatR;
using Microsoft.Extensions.Logging;
using System;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;

namespace B.S.NewMedical.Api.Read.Application.Handler.Order
{
    public class ConsultationPageCommandHandle : IRequestHandler<ConsultationPageCommand, ApiPageing<ConsultationModel>>
    {
        private readonly IBaseRepository<ConsultationModel> _consultationRepository;
        private readonly ILogger<ConsultationPageCommandHandle> _logger;

        public ConsultationPageCommandHandle(
            IBaseRepository<ConsultationModel> consultationRepository,
            ILogger<ConsultationPageCommandHandle> logger)
        {
            _consultationRepository = consultationRepository;
            _logger = logger;
        }

        public async Task<ApiPageing<ConsultationModel>> Handle(ConsultationPageCommand request, CancellationToken cancellationToken)
        {
            try
            {
                _logger.LogInformation("开始查询问诊单分页数据，页码：{Index}，页大小：{Size}", request.Index, request.Size);

                var result = new ApiPageing<ConsultationModel>();

                // 获取所有未删除的问诊单数据
                var query = _consultationRepository.GetAll().Where(x => !x.IsDeleted);

                // 应用查询条件
                if (!string.IsNullOrEmpty(request.Patient))
                {
                    query = query.Where(x => x.Patient != null && x.Patient.Contains(request.Patient));
                }

                if (!string.IsNullOrEmpty(request.Method))
                {
                    query = query.Where(x => x.Method != null && x.Method.Contains(request.Method));
                }

                if (!string.IsNullOrEmpty(request.Source))
                {
                    query = query.Where(x => x.Source != null && x.Source.Contains(request.Source));
                }

                if (!string.IsNullOrEmpty(request.Status))
                {
                    // 注意：ConsultationModel中没有Status字段，只有Orderstatus字段
                    // 这里可以根据实际业务需求调整查询逻辑
                    query = query.Where(x => x.Orderstatus != null && x.Orderstatus.Contains(request.Status));
                }

                if (!string.IsNullOrEmpty(request.Orderstatus))
                {
                    query = query.Where(x => x.Orderstatus != null && x.Orderstatus.Contains(request.Orderstatus));
                }

                // 计算总记录数
                var totalCount = await Task.FromResult(query.Count());

                // 计算总页数
                var totalPage = (int)Math.Ceiling(totalCount / (double)request.Size);

                // 应用分页并获取数据
                var consultations = await Task.FromResult(query
                    .OrderByDescending(x => x.ConsultationTime)
                    .Skip((request.Index - 1) * request.Size)
                    .Take(request.Size)
                    .ToList());
                // 构建返回结果
                result.Code = ApiEnum.Success;
                result.Msg = "查询问诊单列表成功";
                result.TotaCount = totalCount;
                result.TotaPage = totalPage;
                result.PageData = consultations;

                _logger.LogInformation("查询问诊单分页数据完成，总记录数：{TotalCount}，总页数：{TotalPage}", totalCount, totalPage);

                return result;
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "查询问诊单分页数据时发生错误");
                
                return new ApiPageing<ConsultationModel>
                {
                    Code = ApiEnum.Error,
                    Msg = "查询问诊单列表失败：" + ex.Message,
                    TotaCount = 0,
                    TotaPage = 0,
                    PageData = null
                };
            }
        }
    }
}
